package com.happy.gateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;

/**
 * @Auther: lifeng
 * @Date: 2018/12/7 16:10
 * @Description:  限流拦截器 Google的令牌桶算法
 */
public class RateLimitFilter extends ZuulFilter {

  private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
  @Override
  public String filterType() {
    return PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return SERVLET_DETECTION_FILTER_ORDER - 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    RequestContext requestContext = RequestContext.getCurrentContext();
    if(!RATE_LIMITER.tryAcquire()){
      requestContext.setSendZuulResponse(false);
      requestContext.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());
    }
    return null;
  }
}
